import {createRouter, createWebHistory, createWebHashHistory} from 'vue-router'
import home from './modules/home'
import remaining from './modules/remaining'
import useStorage from '@/composables/useStorage'
// import {initRouter} from '@/utils'
import UseMenuStore from '@/store/useMenuStore'
import NProgress from '@/plugins/nprogress'

const router = createRouter({
  history: createWebHistory(),
  routes: [...home, ...remaining]
})
const {get, remove} = useStorage()
/** 路由白名单 */
const whiteList = ['/login']


router.beforeEach((to, from, next) => {
  NProgress.start()
  if (get('token')) {
    if (to.path === '/login') {
      next({path: '/'})
    } else if (UseMenuStore().dynamicMenuList.length === 0) {
      UseMenuStore().initMenu().then((router) => {
        if (!to.name) {
          // 动态路由刷新需要
          router.push(to.fullPath)
        } else {
          //静态路由刷新需要
          next()
        }
        UseMenuStore().addTag(to)
      }).catch(() => {
        remove('token')
        next({
          path: '/login'
        })
      })

    } else {
      next()
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next({
        path: '/login'
      })
    }
  }
  UseMenuStore().addTag(to)
})
router.afterEach(() => {
  NProgress.done()
})
export default router
